﻿#include "ffmpeg_process.h"
#include <QTextStream>
#include <QDateTime>
#include <QtDebug>
#include <QTime>
#include <QDir>
#include <QCoreApplication>

FFmpegProcess::FFmpegProcess(QObject *parent)
    : QObject(parent)
{
    connect(&m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onfinished(int, QProcess::ExitStatus)));
    connect(&m_process, SIGNAL(readyReadStandardError()), this, SLOT(onReadData()));
    m_process.setReadChannel(QProcess::StandardError);
}

void FFmpegProcess::start(const QStringList& argList)
{
    qDebug() << "start process: ffmpeg" << argList;
    m_process.start("ffmpeg", argList);
}

void FFmpegProcess::onReadData()
{
    QString ffmpeglog = m_process.readAllStandardError();
    qDebug() << ffmpeglog;

    m_ffmpegLogs.push_back(ffmpeglog);

    // 从ffmpeg的输出中提取进度，要点是在编码前捕获 Duration 值，并在编码期间捕获 time=... 值。
    QStringList durationList = ffmpeglog.split("Duration: ");
    if(durationList.size() > 1) {
        QString duration = durationList.at(1);
        durationList = duration.split(", start:");
        if (durationList.size() > 1) {
            duration = durationList.at(0);
            //qDebug() << "Duration: " << duration;

            qint64 totalTimeMS = timeStrToMillisecond(duration);
            m_durationMS += totalTimeMS;
            qDebug()  << "Total time:" << totalTimeMS;
        }
    }

    QStringList timeList = ffmpeglog.split("time=");
    if (timeList.size() > 1) {
        QString time = timeList.at(1);
        timeList = time.split(" bitrate=");
        if (timeList.size() > 1) {
            time = timeList.at(0);
        }

        //qDebug()  << "Time:" << time;
        int timeMS = timeStrToMillisecond(time);
        emit onProgress(double(timeMS) / m_durationMS * 100);
        //qDebug()  << "Time:" << timeMS;
        qDebug("Progress: %.02f%", double(timeMS) / m_durationMS * 100);
    }
    // qDebug() <<ffmpeglog;
}

void FFmpegProcess::onfinished(int exitCode, QProcess::ExitStatus exitStatus)
{
    qDebug() << "process finished. exit code: " << exitCode << ", exit status: " << exitStatus;
    emit finished(exitCode, exitStatus);
}

qint64 FFmpegProcess::timeStrToMillisecond(const QString &hhmmss)
{
    QStringList timeList = hhmmss.split(":");
    qint64 time = 0;
    // 00:00:00.14
    if(timeList.size() == 3) {
        time += timeList.at(0).toInt() * 3600 * 1000;
        time += timeList.at(1).toInt() * 60 * 1000;
        time += (qint64)(timeList.at(2).toDouble() * 60 * 1000);
    }
    return time;
}
